A query run fast, but slow from procedure

A query run fast, but slow from procedure


Batch Compilation, Recompilation, and Plan Caching Issues in SQL Server 2005:

"Parameter sniffing" refers to a process whereby SQL Server's execution environment "sniffs" the current parameter values during compilation or recompilation, and passes it along to the query optimizer so that they can be used to generate potentially faster query execution plans. The word "current" refers to the parameter values present in the statement call that caused a compilation or a recompilation.

Boils down to using "local Variables" in your stored procedure queries:

Slow way:
CREATE PROCEDURE GetOrderForCustomers(@CustID varchar(20))
AS
BEGIN
    SELECT *
    FROM orders
    WHERE customerid = @CustID
END

Fast way:
CREATE PROCEDURE GetOrderForCustomersWithoutPS(@CustID varchar(20))
AS
BEGIN
    DECLARE @LocCustID varchar(20)
    SET @LocCustID = @CustID

    SELECT *
    FROM orders
    WHERE customerid = @LocCustID
END

Seyed Hamed Vahedi Seyed Hamed Vahedi     Fri, 2 October, 2020